import { getToken } from '@/utils/auth'
import { resPost } from '@/utils/requestEncy'
const creatWebsocket = {
  heartCheck: {
    timeout: 8000,
    timeoutObj: null,
    serverTimeoutObj: null,
    start() {
      var self = this
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        self.serverTimeoutObj = setTimeout(() => {
          window.websocket.close()
        }, self.timeout)
      }, this.timeout)
    }
  },
  lockReconnect: false, // 避免重复连接
  ws: null,
  tt: null,
  constructor: {},
  userId: '',
  /**
   * 创建WebSocket
   */
  creadWebSocket(ths, userId) {
    const _this = this
    this.constructor = ths
    this.userId = userId
    try {
      // window.websocket = new WebSocket('ws://' + location.host + '/websocket/' + (cookie.get('dgwjToken') ? cookie.get('dgwjToken') : 'sessionId'))// 外网
      window.websocket = new WebSocket('ws://192.168.107.1:18003/wsauth/' + getToken())// 外网
      _this.init()
    } catch (e) {
      console.log('catch')
      this.reconnect()
    }
  },
  init() {
    const _this = this
    // 连接发生错误的回调方法
    window.websocket.onerror = () => {
      console.log('WebSocket连接发生错误')
      _this.reconnect()
    }

    // 连接成功建立的回调方法
    window.websocket.onopen = () => {
      console.log('WebSocket连接成功')
      const obj = resPost({ headers: {} }, { 'wxType': 'SYSMESSAGE' })
      const param = {
        ttsxbwqm: obj.headers.ttsxbwqm,
        ttsxsjzc: obj.headers.ttsxsjzc,
        ttsxyhcs: obj.headers.ttsxyhcs,
        wxType: 'SYSMESSAGE'
      }
      window.websocket.send(JSON.stringify(param))
      // _this.heartCheck.start()
    }
    // 接收到消息的回调方法
    window.websocket.onmessage = (event) => {
      try {
        _this.constructor.$store.commit('CHANG_SOCKET_DATA', event.data)
      } catch (err) {
        console.log(err)
      }
      // _this.heartCheck.start()
    }
    // 连接关闭的回调方法
    window.websocket.onclose = (e) => {
      _this.reconnect()
    }
  },
  reconnect() {
    const _this = this
    if (this.lockReconnect) {
      return
    }
    this.lockReconnect = true
    // 没连接上会一直重连，设置延迟避免请求过多
    this.tt && clearTimeout(this.tt)
    this.tt = setTimeout(() => {
      _this.creadWebSocket(_this.constructor, this.userId)
      _this.lockReconnect = false
    }, 4000)
  }
}
export default creatWebsocket
